package mrpanyu.guitool.selectionreplace;

import java.io.IOException;
import java.io.Writer;

import mrpanyu.guitool.base.model.Tool;

public class ToolWriter extends Writer {

	private Tool tool;
	private boolean errorWriter;
	private StringBuilder buf = new StringBuilder();

	public ToolWriter(Tool tool, boolean errorWriter) {
		this.tool = tool;
		this.errorWriter = errorWriter;
	}

	@Override
	public void write(char[] cbuf, int off, int len) throws IOException {
		buf.append(cbuf, off, len);
		int lfIndex = buf.indexOf("\n");
		while (lfIndex >= 0) {
			String line = buf.substring(0, lfIndex);
			if (errorWriter) {
				tool.errorMessage(line);
			} else {
				tool.infoMessage(line);
			}
			buf.delete(0, lfIndex + 1);
			lfIndex = buf.indexOf("\n");
		}
	}

	@Override
	public void flush() throws IOException {
	}

	@Override
	public void close() throws IOException {
		if (buf.length() > 0) {
			if (errorWriter) {
				tool.errorMessage(buf.toString());
			} else {
				tool.infoMessage(buf.toString());
			}
		}
	}

}
